import 'package:film/controller/auth_controller.dart';
import 'package:film/model/sys_model.dart';
import 'package:film/service/api_service.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class MemberController extends GetxController {
  final AuthController authController = Get.put(AuthController());
  final DioService dioService = DioService();
  final TextEditingController nicknameController = TextEditingController();
  var userImgList = [].obs;
  var nickname = ''.obs;
  var userImg = ''.obs;
  var isLoading = false.obs;

  @override
  void onInit() {
    nicknameController.text = authController.userInfo.value.nickname ?? '';
    userImg.value = authController.userInfo.value.userImg ?? 'https://i.postimg.cc/8zWJyD2j/luffy.png';
    getUserImgList();
    super.onInit();
  }

  @override
  void onClose() {
    nicknameController.dispose();
    super.onClose();
  }

  // 获取头像
  void getUserImgList() async {
    final ApiResponse<SysModel> response = await dioService.getSysInfo();
    if (response.success) {
      userImgList.assignAll(response.data?.userImg ?? []);
    }
  }

  // 选择头像
  void selectUserImg(String url) {
    userImg.value = url;
    Get.back();
  }

  // 更新个人资料
  Future<void> updateUserInfo() async {
    if (nicknameController.text.isEmpty) {
      Get.snackbar(
        '错误',
        '昵称不能为空',
        duration: Duration(seconds: 1),
      );
      return;
    }
    isLoading.value = true;
    final newNickname = nicknameController.text.trim();
    final ApiResponse<void> response = await dioService.updateUserInfo(
      nickname: newNickname,
      userImg: userImg.value,
    );
    if (response.success) {
      authController.userInfo.value.nickname = newNickname;
      authController.userInfo.value.userImg = userImg.value;
      authController.userInfo.refresh();
      Get.back();
      Get.snackbar(
        '成功',
        '个人资料已更新！',
        duration: Duration(seconds: 1),
      );
    }
    isLoading.value = false;
  }
}
